﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace NewTools
{
    internal class AutoThread
    {
        private MainWindow mMainWindow = null;
        private bool mRunning = false;
        private readonly ParseIni mParseIni = null;
        private string mFloderName;

        public AutoThread(MainWindow mainWindow, string floderName)
        {
            this.mMainWindow = mainWindow;
            this.mParseIni = new ParseIni();
            this.mFloderName = floderName;
        }

        public void SetFloderName(string floderName)
        {
            this.mFloderName = floderName;
        }

        public void AutoRun()
        {
            Int32   index = 0;
            Int32   sleepValue = 0;
            string  cmdValue = null;
            string  cmdName = null;
            try
            {
                mRunning = true;
                Int32 num = mParseIni.AutoRunCommandNumber_Get(this.mFloderName);
                
                while (mRunning && index < num)
                {
                    sleepValue = mParseIni.AutoRunSleepValue_Get(index, mFloderName);
                    cmdValue = mParseIni.AutoRunStringCommandById_Get(index, mFloderName);
                    cmdName = mParseIni.AutoRunStringCommandNameById_Get(index, mFloderName);
                
                    mMainWindow.mSynchronizationContext.Post(new SendOrPostCallback(mMainWindow.ExecuteAutoCommand), index);
                    index++;
                    Thread.Sleep(sleepValue);
                }
                mRunning = false;
                mMainWindow.mSynchronizationContext.Post(new SendOrPostCallback(mMainWindow.ThreadExit), null);
            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void exitAutoRunThread()
        {
            mRunning = false;
        }
    }
}
